package cn.neusoft.myproject.service.impl;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import cn.neusoft.myproject.config.MediumConfig;
import cn.neusoft.myproject.dao.UserDao;
import cn.neusoft.myproject.domain.FileDO;
import cn.neusoft.myproject.domain.UserDO;
import cn.neusoft.myproject.service.FileService;
import cn.neusoft.myproject.service.UserService;
import cn.neusoft.myproject.utils.FileType;
import cn.neusoft.myproject.utils.FileUtil;
import cn.neusoft.myproject.utils.ImageUtils;
import cn.neusoft.myproject.utils.MD5Utils;
import cn.neusoft.myproject.utils.UserVO;

@Transactional
@Service
public class UserServiceImpl implements UserService {
  private static final Logger logger = LoggerFactory.getLogger(UserService.class);

  @Autowired
  UserDao userMapper;
  @Autowired
  private FileService sysFileService;
  @Autowired
  private MediumConfig bootdoConfig;

  public static void main(String[] args) {
    String pwd = MD5Utils.encrypt("admin", "admin");
    System.out.println(pwd);
  }

  @Override
  public UserDO get(Long id) {
    UserDO user = userMapper.get(id);
    return user;
  }

  @Override
  public List<UserDO> list(Map<String, Object> map) {
    return userMapper.list(map);
  }

  @Override
  public int count(Map<String, Object> map) {
    return userMapper.count(map);
  }

  @Transactional
  @Override
  public int save(UserDO user) {
    return userMapper.save(user);
  }

  @Override
  public int update(UserDO user) {
    return userMapper.update(user);
  }

  @Override
  public int remove(Long userId) {
    return userMapper.remove(userId);
  }

  @Override
  public boolean exit(Map<String, Object> params) {
    boolean exit;
    exit = userMapper.list(params).size() > 0;
    return exit;
  }

  @Override
  public int resetPwd(UserVO userVO, UserDO userDO) throws Exception {
    if (Objects.equals(userVO.getUserDO().getUserId(), userDO.getUserId())) {
      if (Objects
        .equals(MD5Utils.encrypt(userDO.getUsername(), userVO.getPwdOld()), userDO.getPassword())) {
        userDO.setPassword(MD5Utils.encrypt(userDO.getUsername(), userVO.getPwdNew()));
        return userMapper.update(userDO);
      } else {
        throw new Exception("输入的旧密码有误！");
      }
    } else {
      throw new Exception("你修改的不是你登录的账号！");
    }
  }

  @Override
  public int adminResetPwd(UserVO userVO) throws Exception {
    UserDO userDO = get(userVO.getUserDO().getUserId());
    if ("admin".equals(userDO.getUsername())) {
      throw new Exception("超级管理员的账号不允许直接重置！");
    }
    userDO.setPassword(MD5Utils.encrypt(userDO.getUsername(), userVO.getPwdNew()));
    return userMapper.update(userDO);

  }

  @Transactional
  @Override
  public int batchremove(Long[] userIds) {
    int count = userMapper.batchRemove(userIds);
    return count;
  }

  @Override
  public int updatePersonal(UserDO userDO) {
    return userMapper.update(userDO);
  }

  @Override
  public Map<String, Object> updatePersonalImg(MultipartFile file, String avatar_data, Long userId)
    throws Exception {
    String fileName = file.getOriginalFilename();
    fileName = FileUtil.renameToUUID(fileName);
    FileDO sysFile = new FileDO(FileType.fileType(fileName), "/files/" + fileName, new Date());
    //获取图片后缀
    String prefix = fileName.substring((fileName.lastIndexOf(".") + 1));
    String[] str = avatar_data.split(",");
    //获取截取的x坐标
    int x = (int) Math.floor(Double.parseDouble(str[0].split(":")[1]));
    //获取截取的y坐标
    int y = (int) Math.floor(Double.parseDouble(str[1].split(":")[1]));
    //获取截取的高度
    int h = (int) Math.floor(Double.parseDouble(str[2].split(":")[1]));
    //获取截取的宽度
    int w = (int) Math.floor(Double.parseDouble(str[3].split(":")[1]));
    //获取旋转的角度
    int r = Integer.parseInt(str[4].split(":")[1].replaceAll("}", ""));
    try {
      BufferedImage cutImage = ImageUtils.cutImage(file, x, y, w, h, prefix);
      BufferedImage rotateImage = ImageUtils.rotateImage(cutImage, r);
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      boolean flag = ImageIO.write(rotateImage, prefix, out);
      //转换后存入数据库
      byte[] b = out.toByteArray();
      FileUtil.uploadFile(b, bootdoConfig.getUploadPath(), fileName);
    } catch (Exception e) {
      throw new Exception("图片裁剪错误！！");
    }
    Map<String, Object> result = new HashMap<>();
    if (sysFileService.save(sysFile) > 0) {
      UserDO userDO = new UserDO();
      userDO.setUserId(userId);
      userDO.setPicId(sysFile.getId());
      if (userMapper.update(userDO) > 0) {
        result.put("url", sysFile.getUrl());
      }
    }
    return result;
  }
}
